import tkinter as tk

class computer:
    def __init__(self, master):
        self.master = master
        master.title("计算器")
        # 表格五行四列
        self.entry = tk.Entry(master, width=30, justify='right')
        self.entry.insert('end',0)
        self.entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

        buttons = [
            'C', '(', ')', '+',
            '7', '8', '9', '-',
            '4', '5', '6', '*',
            '1', '2', '3', '/',
            '0', '.', '%', '='
        ]

        row_val = 1
        col_val = 0
        # 循环显示按钮
        for button in buttons:
            # 等号表示计算
            if button == '=':
                tk.Button(master, text=button, width=10, command=lambda: self.run()).grid(row=row_val, column=col_val, padx=5, pady=5)
            # C表示清零 
            elif button == 'C':
                tk.Button(master, text=button, width=10, command=lambda: self.res()).grid(row=row_val, column=col_val, padx=5, pady=5)
            else:
                tk.Button(master, text=button, width=10, command=lambda b=button: self.add(b)).grid(row=row_val, column=col_val, padx=5, pady=5)
            col_val += 1
            if col_val > 3:
                col_val = 0
                row_val += 1

    # 归零
    def res(self):
        self.entry.delete(0, 'end')
        self.entry.insert('end', 0)

    # 添加数字或运算符
    def add(self, char):
        box = self.entry.get()
        if box == '0':
            self.entry.delete(0, 'end')
        self.entry.insert('end', char)

    # 运算
    def run(self):
        try:
            result = eval(self.entry.get())
            self.entry.delete(0, 'end')
            self.entry.insert(0, str(result))
        except Exception as e:
            self.entry.delete(0, 'end')
            self.entry.insert(0, '错误')

root = tk.Tk()
cmd = computer(root)
root.mainloop()